package com.ruoyi.system.utils;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class Md5Utils {
    private static final char[] HEX_DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public Md5Utils() {
    }

    private static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);

        for(int i = 0; i < b.length; ++i) {
            sb.append(HEX_DIGITS[(b[i] & 240) >>> 4]);
            sb.append(HEX_DIGITS[b[i] & 15]);
        }

        return sb.toString();
    }

    public static String md5(String astr) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(astr.getBytes());
        byte[] messageDigest = digest.digest();
        return toHexString(messageDigest);
    }

    public static String getFileMD5(String filePath) {
        try {
            FileInputStream inputStream = new FileInputStream(filePath);
            return getFileMD5((InputStream)inputStream);
        } catch (Exception var2) {
            var2.printStackTrace();
            return null;
        }
    }

    public static String getFileMD5(InputStream inputStream) {
        try {
            String md5 = DigestUtils.md5Hex(inputStream);
            inputStream.close();
            return md5;
        } catch (Exception var2) {
            var2.printStackTrace();
            return null;
        }
    }
}
